<script setup>
import {ref, computed} from 'vue';
import {useUserStore} from '@/stores/user.js'; // 获取用户 buyerId
import {getExchangeListAPI, cancelExchangeAPI} from '@/api/Trade.js'; // 请求函数
import {ElMessage} from 'element-plus';
import {formatDate} from '@/utils/format.js'

const userStore = useUserStore();
const exchangeOrderList = ref([]); // 存储订单数据
const activeOrderId = ref(null); // 控制展开状态的订单id
const filterStatus = ref(0); // 当前过滤的状态

// 获取交换订单列表
const getExchangeOrders = async () => {
  try {
    const UserId = userStore.UserId; // 从 stores 获取 buyerId
    console.log("获取交换订单列表，buyerId：", UserId);

    const response = await getExchangeListAPI(UserId);
    console.log("获取交换订单列表成功：", response);
    if (response.data.code === 200) {
      exchangeOrderList.value = response.data.data;
      console.log("订单列表：", exchangeOrderList);
    }
  } catch (error) {
    console.error("获取交换订单失败：", error);
    ElMessage.error("获取交换订单失败");
  }
};

// 切换订单的展开状态
const toggleExchangeGoods = (orderId) => {
  activeOrderId.value = activeOrderId.value === orderId ? null : orderId;
};

// 取消交换订单
const cancelExchangeOrder = async (orderId) => {
  try {
    // 使用 MessageBox 进行确认
    const result = await ElMessageBox.confirm(
        '确认取消该订单吗？',
        '确认取消',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    // 如果用户确认，继续执行取消订单的逻辑
    if (result === 'confirm') {
      const response = await cancelExchangeAPI(orderId);
      if (response.data.code === 200) {
        ElMessage.success("订单取消成功");
        await getExchangeOrders(); // 刷新订单列表
      }
    }
  } catch (error) {
    // 用户点击取消或其他错误
    if (error === 'cancel') {
      console.log("用户取消了操作");
    } else {
      console.error("取消订单失败：", error);
      ElMessage.error("取消订单失败");
    }
  }
};
// 过滤订单
const filteredExchangeOrderList = computed(() => {
  return exchangeOrderList.value.filter(order => order.status === filterStatus.value);
});

// 页面加载时获取订单数据
getExchangeOrders();
</script>

<template>
  <div>
    <!-- 过滤器 -->
    <el-radio-group v-model="filterStatus" style="margin-bottom: 20px; width:150%; margin-left:-5%; margin-top: 40px;">
      <el-radio-button :label="0">待交换</el-radio-button>
      <el-radio-button :label="1">已完成</el-radio-button>
      <el-radio-button :label="2">已取消</el-radio-button>
      <el-radio-button :label="3">已拒绝</el-radio-button>
      <el-radio-button :label="4">已发货</el-radio-button>
    </el-radio-group>

    <el-collapse v-model="activeOrderId" accordion>
      <el-collapse-item
          v-for="(order) in filteredExchangeOrderList"
          :key="order.id"
          :name="order.id"
          class="order-card"
      >
        <template #title>
          <!-- 商品信息 -->
          <el-table :data="[order]" style="width: 100%; margin-top: 30px;">
            <el-table-column label="商品图片" width="150" v-slot="scope">
              <img :src="scope.row.goodsImage" alt="商品图片" class="order-image"/>
            </el-table-column>

            <el-table-column prop="goodsName" label="商品名称" width="150"/>
            <el-table-column prop="price" label="价格" width="100">
              <template #default="scope">
                <span style="color: blue">{{ scope.row.price }} 元</span>
              </template>
            </el-table-column>

            <el-table-column prop="description" label="描述"/>
<!--            创建时间-->
            <el-table-column prop="createTime" label="创建时间" width="150">
              <template #default="scope">
                <span >{{ formatDate(scope.row.createTime) }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="goodsNums" label="数量" width="100">
              <template #default="scope">
                <span >{{ scope.row.goodsNum }}</span>
              </template>
            </el-table-column>

            <el-table-column v-if="order.status === 0" label="操作" width="100">
              <template #default="scope">
                <el-button type="danger" @click="cancelExchangeOrder(order.id)">取消交换</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>

        <!-- 交换商品列表 -->
        <div class="exchange-goods-list">
          <h3>交换商品：</h3>
          <el-table :data="order.exchangeGoodsList" style="width: 100%;">
            <el-table-column width="150" v-slot="scope">
              <img :src="scope.row.image || 'default-image-url.jpg'" alt="交换商品图片" class="exchange-goods-image"/>
            </el-table-column>
            <el-table-column prop="name" label="名称" width="150"/>
            <el-table-column prop="price" label="价格" width="100"/>
            <el-table-column prop="description" label="描述"/>
            <el-table-column prop="exchangeGoodsNums" label="数量" width="120"/>
          </el-table>
        </div>

        <!-- 地址信息展示为表格 -->
        <div class="address-info">
          <h3>收货地址：</h3>
          <el-table :data="[order.mailAddress]" style="width: 100%; margin-top: 10px;">
            <el-table-column prop="addressee" label="收件人" width="150"/>
            <el-table-column prop="addresseePhone" label="联系电话" width="150"/>
            <el-table-column prop="address" label="地址"/>
          </el-table>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<style scoped>
.order-card {
  border-radius: 8px;
  margin-top: 80px; /* 订单之间的间距 */
  width: 1000px;
  padding: 20px;
  background-color: #f9f9f9;
  margin-left: -15%;
  transition: all 0.3s ease; /* 添加过渡效果 */
}

.order-info {
  display: flex;
  align-items: center;
}

.order-image {
  width: 100px;
  height: 100px;
  margin-right: 20px;
  border-radius: 8px;
}

.exchange-goods-list {
  margin-top: 40px;
  padding-top: 20px;
}

.exchange-goods-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.el-collapse-item__wrap {
  overflow: visible; /* 确保内容不会被隐藏 */
  margin-bottom: 30px; /* 订单之间的间距 */
}

.el-collapse-item {
  margin-bottom: 20px; /* 每个订单之间的额外间距 */
}

.el-table {
  margin-bottom: 20px; /* 表格和底部内容的间距 */
}

.el-table__body-wrapper {
  border-radius: 8px; /* 圆角效果 */
}
</style>